package ldh.im.fxbase.util;

import java.util.*;
import java.util.function.BiFunction;

public class MapUtil {

    public static <K, V> Map<K, V> sortMapByValue(Map<K, V> oriMap, BiFunction<V, V, Integer> comparable) {
        Map<K, V> sortedMap = new LinkedHashMap<K, V>();
        if (oriMap != null && !oriMap.isEmpty()) {
            List<Map.Entry<K, V>> entryList = new ArrayList<Map.Entry<K, V>>(oriMap.entrySet());
            Collections.sort(entryList, (e1, e2)-> comparable.apply(e1.getValue(), e2.getValue()));
            Iterator<Map.Entry<K, V>> iter = entryList.iterator();
            Map.Entry<K, V> tmpEntry = null;
            while (iter.hasNext()) {
                tmpEntry = iter.next();
                sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
            }
        }
        return sortedMap;
    }

    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap();
        map.put("t1", 10);
        map.put("t2", 20);
        map.put("t3", 5);
        map = MapUtil.sortMapByValue(map, (i1, i2)->i2-i1);
        map.forEach((k, v)->System.out.println(String.format("k:%s, v: %s", k, v)));
    }
}
